#include "configRequest.h"
size_t configCallback(void *contents, size_t size, size_t nmemb, void *userp) 
{
    size_t realsize = size *nmemb;
    //处理获取到的数据，比如存储到文件或者其他操作
    char * result = (char*)contents;
    printf("%s\n",result);
    cJSON *jsonstr = cJSON_Parse(result);
    if(jsonstr != NULL){
        cJSON *successRoot = cJSON_GetObjectItemCaseSensitive(jsonstr,"success");
        cJSON *codeRoot = cJSON_GetObjectItemCaseSensitive(jsonstr,"code");
        cJSON *messageRoot = cJSON_GetObjectItemCaseSensitive(jsonstr,"message");
        if(cJSON_IsTrue(successRoot)){
            printf("%s\n",messageRoot->valuestring);    
        }
        cJSON *dataRoot = cJSON_GetObjectItemCaseSensitive(jsonstr,"data");
        cJSON *adList = cJSON_GetObjectItemCaseSensitive(dataRoot,"ad_list");
        cJSON *cmdList = cJSON_GetObjectItemCaseSensitive(dataRoot,"cmd_list");
        //解析指令集
        parseCmd(cmdList);
    }
    return realsize;
}
void sendConfigRequest(){
    //读取当前文件目录下面的config.ini获取devinfo_path地址
    GKeyFile *configiniPath = g_key_file_new();
    if(!g_key_file_load_from_file(configiniPath,"./config.ini",G_KEY_FILE_NONE,NULL)){
        g_warning("load config.ini error!");
        return;
    }
    gchar *path = g_key_file_get_string(configiniPath,"config","devinfo_path",NULL);
    g_key_file_free(configiniPath);

    //从devinfo_path指定的文件中读取ip和地址
    GKeyFile *configPath = g_key_file_new();
    if(!g_key_file_load_from_file(configPath,path,G_KEY_FILE_NONE,NULL)){
        g_warning("load config.ini error!");
        return;
    }
    gchar *gatewayIp = g_key_file_get_string(configPath,"config","gatewayIp",NULL);
    gchar *location = g_key_file_get_string(configPath,"config","location",NULL);
    g_key_file_free(configPath);
    char *url = "http://%s/config.json?sn=1205556&location=%s";
    char * realUrl = calloc(1,100);
    sprintf(realUrl,url,gatewayIp,location);
    printf("request address:%s\n",realUrl);
    sendGetRequest(realUrl,configCallback);
}